<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" @clear="doSearch" />
      <el-button type="primary" @click="doSearch">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/addExterprise')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list">
        <el-table-column type="index" label="序号" :index="indexMethod" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          label="联系电话"
          prop="contactNumber"
        />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="mini" type="text" @click="addRent(scope.row.id)">添加合同</el-button>
            <el-button size="mini" type="text">查看</el-button>
            <el-button size="mini" type="text" @click="editRent(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="delExterprise(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :page-size="params.pageSize"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- // 添加合同弹框 -->
    <!-- title:控制左上角的文本
      visible:控制弹框的显示与隐藏
      close事件:弹框关闭时会执行close后面的处理函数 -->
    <el-dialog
      title="添加合同"
      :visible="rentDialogVisible"
      width="580px"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <!-- 表单区域 -->
      <!-- 表单模版 -->
      <div class="form-container">
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in buildList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <!-- 配置默认上传的地址，必须要配置，如果不配置加一个#号 -->
            <!-- http-request 覆盖默认上传 -->
            <!-- before-upload 上传前的钩子 -->
            <!-- limit 上传文件数量限制 -->
            <!-- on-exceed 文件超出limit限制的个数时执行的钩子 -->
            <!-- on-remove 文件移除时会自动执行 -->
            <el-upload
              action="#"
              :http-request="uploadHandle"
              :before-upload="beforeUpload"
              :limit="1"
              :on-exceed="onExceed"
              :on-remove="onRemove"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmContract">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getEnterpriseListAPI, delExterpriseAPI, getRentBuildingAPI, createRentAPI } from '@/api/enterprise'
import { uploadAPI } from '@/api/common'
export default {
  name: 'EnterPrise',
  data() {
    return {
      params: {
        name: '',
        page: 1,
        pageSize: 2
      },
      list: [],
      total: 0,
      // 控制弹框的显示影藏
      rentDialogVisible: false,
      rentForm: {
        buildingId: null, // 楼宇id
        startTime: '',
        endTime: '',
        rentTime: [], // 租赁时间
        contractUrl: '', // 合同url
        contractId: null, // 合同id
        type: 0, // 操作类型
        enterpriseId: null // 企业id
      },
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'blur' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'blur' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件', trigger: 'blur' }
        ]
      },
      buildList: []

    }
  },
  created() {
    this.getEnterpriseList()
  },

  methods: {
    onRemove() {
      // console.log('移除了文件')
      this.rentForm.contractId = ''
      this.rentForm.contractUrl = ''
      this.$refs.addForm.validateField('contractId')
    },
    // 添加租赁合同
    confirmContract() {
      this.$refs.addForm.validate(async(flag) => {
        if (!flag) {
          this.$message.error('请完善表单信息！')
          return
        }
        // 提交接口
        const [startTime, endTime] = this.rentForm.rentTime
        this.rentForm.startTime = startTime
        this.rentForm.endTime = endTime
        delete this.rentForm.rentTime
        // 添加调试信息，确认表单数据完整
        console.log('提交前的完整表单数据:')
        console.log('enterpriseId:', this.rentForm.enterpriseId)
        console.log('buildingId:', this.rentForm.buildingId)
        console.log('startTime:', this.rentForm.startTime)
        console.log('endTime:', this.rentForm.endTime)
        console.log('contractUrl:', this.rentForm.contractUrl)
        console.log('contractId:', this.rentForm.contractId)
        console.log('type:', this.rentForm.type)

        await createRentAPI(this.rentForm)
        this.$message.success('租赁合同添加成功!')
        // 关闭弹框
        this.closeDialog()
        this.getEnterpriseList()
        // console.log(res)
      })
    },
    // 超出限制数是的提示
    onExceed() {
      this.$message.warning('文件上传限制数量为1!')
    },
    // 上传文件前执行的钩子函数
    beforeUpload(file) {
      console.log(file)
      const allowFileType = ['application/msword', 'text/plain', 'application/pdf'].includes(file.type)
      const lt5m = file.size / 1024 / 1024 < 5
      if (!allowFileType) {
        this.$message.error('上传的文件必须是txt,doc,pdf格式!')
      }
      if (!lt5m) {
        this.$message.error('上传的文件大小需小于5M!')
      }
      return allowFileType && lt5m
    },
    // 上传文件
    async uploadHandle({ file }) {
      // console.log(file)
      const formDate = new FormData()
      formDate.append('file', file)
      formDate.append('type', 'contract')
      const { data } = await uploadAPI(formDate)
      // console.log(data)
      this.rentForm.contractId = data.id
      this.rentForm.contractUrl = data.url
      this.$refs.addForm.validateField(this.rentForm.contractId)
    },
    // 点击创建合同
    async addRent(id) {
      // 打开弹框
      this.rentDialogVisible = true
      this.rentForm.enterpriseId = id
      console.log(this.rentForm.enterpriseId)
      // 获取楼宇下拉列表
      const res = await getRentBuildingAPI()
      // console.log(res)
      this.buildList = res.data
    },
    // 弹框关闭后执行
    closeDialog() {
      this.rentDialogVisible = false
      // 清空校验提示
      this.$refs.addForm.resetFields()
      // 清空数据
      this.rentForm = {
        buildingId: null, // 楼宇id
        startTime: '',
        endTime: '',
        rentTime: [], // 租赁时间
        contractUrl: '', // 合同url
        contractId: null, // 合同id
        type: 0, // 操作类型
        enterpriseId: null // 企业id
      }
    },
    // 删除 再租企业不能删除
    delExterprise(id) {
      this.$confirm('确定删除该企业吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delExterpriseAPI(id)
        if (this.list.length === 1 && this.params.page > 1) {
          this.params.page--
        }

        this.getEnterpriseList()
        this.$message.success('删除成功！')
      }).catch(() => {})
    },
    // 点击编辑按钮，进行跳转 / 也叫查询参数传参
    editRent(id) {
      // console.log(id)
      this.$router.push({
        path: '/addExterprise',
        query: {
          id
        }
      })
    },
    // 模糊搜索
    doSearch() {
      // 重置页码
      this.params.page = 1
      this.getEnterpriseList()
    },
    // 设置序号
    indexMethod(index) {
      return (index + 1) + (this.params.page - 1) * this.params.pageSize
    },
    // 页码发生变化时执行
    handleCurrentChange(val) {
      console.log(val)
      this.params.page = val
      this.getEnterpriseList()
    },
    // 页容量发生变化时执行
    // handleSizeChange(val) {
    //   console.log(val)
    //   this.params.pageSize = val
    // },
    async getEnterpriseList() {
      const res = await getEnterpriseListAPI(this.params)
      console.log(res)
      this.list = res.data.rows
      this.total = res.data.total
    }

  }

}
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
